package com.message.util;

import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest;
import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiMessageCorpconversationAsyncsendV2Request;
import com.dingtalk.api.request.OapiV2DepartmentListsubRequest;
import com.dingtalk.api.request.OapiV2DepartmentListsubidRequest;
import com.dingtalk.api.request.OapiV2UserListRequest;
import com.dingtalk.api.response.OapiMessageCorpconversationAsyncsendV2Response;
import com.dingtalk.api.response.OapiV2DepartmentListsubResponse;
import com.dingtalk.api.response.OapiV2DepartmentListsubidResponse;
import com.dingtalk.api.response.OapiV2UserListResponse;
import com.message.config.ConfigProperties;
import com.message.domain.MessageSourceDto;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class DingdingUtil {

    /**
     * 获取企业内部应用的accessToken
     *
     * @return
     * @throws Exception
     */
    public static String getAccessToken() {
        com.aliyun.dingtalkoauth2_1_0.Client client = null;
        try {
            client = createClient();
        } catch (Exception e) {
            e.printStackTrace();
        }
        GetAccessTokenRequest getAccessTokenRequest = new GetAccessTokenRequest()
                .setAppKey(ConfigProperties.getPropertyValue("dingding.appid"))
                .setAppSecret(ConfigProperties.getPropertyValue("dingding.appkey"));
        try {
            GetAccessTokenResponse accessToken = client.getAccessToken(getAccessTokenRequest);
            System.out.println(accessToken);
            return accessToken.getBody().accessToken;
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
            }
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
            }
            _err.printStackTrace();
        }
        return "";
    }

    public static com.aliyun.dingtalkoauth2_1_0.Client createClient() throws Exception {
        Config config = new Config();
        config.protocol = "https";
        config.regionId = "central";
        return new com.aliyun.dingtalkoauth2_1_0.Client(config);
    }

    /**
     * 获取部门列表
     */
    public static List<Long> getDepList(String access_token) {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/listsub");
        OapiV2DepartmentListsubRequest req = new OapiV2DepartmentListsubRequest();
        req.setDeptId(1L);
        req.setLanguage("zh_CN");
        OapiV2DepartmentListsubResponse rsp = null;
        try {
            rsp = client.execute(req, access_token);
        } catch (ApiException e) {
            e.printStackTrace();
        }
        if (rsp.getResult().isEmpty()) {
            return null;
        }
        //所有父部门id列表
        List<Long> parentids = rsp.getResult().stream().map(e -> e.getDeptId()).collect(Collectors.toList());
        //所有部门编号
        List<Long> alldepIds = new ArrayList<>();
        for (int i = 0, len = parentids.size(); i < len; i++) {
            getsubDepList(alldepIds, parentids.get(i), access_token);
        }

        return alldepIds;

    }

    /**
     * 获取所有部门下的子部门编号
     *
     * @param subdepts
     * @param parentId
     * @param access_token
     */
    public static void getsubDepList(List<Long> subdepts, Long parentId, String access_token) {
        if (parentId != null) {
            subdepts.add(parentId);
        }
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/listsubid");
            OapiV2DepartmentListsubidRequest req = new OapiV2DepartmentListsubidRequest();
            req.setDeptId(parentId);
            OapiV2DepartmentListsubidResponse rsp = client.execute(req, access_token);
            List<Long> deptIdList = rsp.getResult().getDeptIdList();
            if (deptIdList != null && deptIdList.size() != 0) {
                subdepts.addAll(deptIdList);
                for (int i = 0, len = deptIdList.size(); i < len; i++) {
                    getsubDepList(subdepts, deptIdList.get(i), access_token);
                }
            }
        } catch (ApiException e) {
            e.printStackTrace();
        }

    }

    /**
     * 获取部门用户列表
     */

    public static List<OapiV2UserListResponse.ListUserResponse> getDepuserIdList(long depId, String access_token) {
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/list");
            OapiV2UserListRequest req = new OapiV2UserListRequest();
            req.setDeptId(depId);
            req.setCursor(0l);
            req.setSize(100l);
            OapiV2UserListResponse rsp = client.execute(req, access_token);
            OapiV2UserListResponse.PageResult result = rsp.getResult();
            return result.getList();
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 发送工作通知消息
     */
    public static void sendWorkmessage(MessageSourceDto messageSourceDto) {
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");
            OapiMessageCorpconversationAsyncsendV2Request req = new OapiMessageCorpconversationAsyncsendV2Request();
            req.setAgentId(ConfigProperties.getPropertyLongValue("dingding.agentId"));
            req.setUseridList(messageSourceDto.getTouserId());
            OapiMessageCorpconversationAsyncsendV2Request.Msg obj1 = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
            obj1.setMsgtype("text");
            OapiMessageCorpconversationAsyncsendV2Request.Text obj2 = new OapiMessageCorpconversationAsyncsendV2Request.Text();
            obj2.setContent(messageSourceDto.getMsg());
            obj1.setText(obj2);
            req.setMsg(obj1);
            OapiMessageCorpconversationAsyncsendV2Response rsp = client.execute(req, messageSourceDto.getToken());
            log.info("消息编号："+messageSourceDto.getId()+rsp.getBody());
        } catch (ApiException e) {
            log.error("消息编号："+messageSourceDto.getId()+"发送失败");
            e.printStackTrace();
        }
    }


}


